import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Result, Button } from 'antd';
import type { User } from '../types';

interface ProtectedRouteProps {
  children: React.ReactNode;
  currentUser: User | null;
  requiredRole?: 'admin' | 'user';
  fallbackPath?: string;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  currentUser,
  requiredRole,
  fallbackPath = '/login',
}) => {
  const location = useLocation();

  // 检查用户是否已登录
  if (!currentUser) {
    return <Navigate to={fallbackPath} state={{ from: location }} replace />;
  }

  // 检查角色权限
  if (requiredRole && currentUser.role !== requiredRole) {
    return (
      <Result
        status="403"
        title="403"
        subTitle="抱歉，您没有权限访问此页面。"
        extra={
          <Button type="primary" onClick={() => window.history.back()}>
            返回
          </Button>
        }
      />
    );
  }

  return <>{children}</>;
};

export default ProtectedRoute; 